package com.sgb.kjwl.view.ui.activity.self;

import android.content.DialogInterface;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityGasStationBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.GasStationInfoEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.adapter.self.GasImageAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.GasStationImageAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.StationServierAdapter;
import com.sgb.kjwl.view.widget.MapAdressDialog;
import com.sgb.kjwl.viewmodel.self.StationModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 加油站基础信息
 */
public class AddGasStationActivity extends AppActivity {
    ActivityGasStationBinding binding;
    @Inject
    StationModel stationModel;

    List<String> serviceInfo = new ArrayList<>();
    // 一级联动数据
    public static List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public static List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public static List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    StationServierAdapter adapter;
    GasStationImageAdapter imageAdapter;
    private List<String> urls = new ArrayList<>();
    private List<File> fileList = new ArrayList<>();
    private List<String> uploadStationImgList = new ArrayList<>();
    private int currentImgNum;
    private int type;
    String chemicalsPic = "";
    String licensePic = "";
    String businessLicensePic = "";
    GasImageAdapter gasImageAdapter;

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_gas_station);

        binding.include.titleView.setText("加油站基础信息");

        binding.include.ivBack.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.tvAdd.setOnClickListener(this);
        binding.llAdress.setOnClickListener(this);
        adapter = new StationServierAdapter(getActivity(), null);
        binding.recyclerService.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.recyclerService.addItemDecoration(new RecyclerViewItemDecoration(getResources().getDimension(R.dimen.dp1)));
        binding.recyclerService.setAdapter(adapter);

        binding.recyclerStation.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        imageAdapter = new GasStationImageAdapter(this, null, null, 3);
        imageAdapter.setDatas(null, urls);
        imageAdapter.setFileList(fileList);
        binding.recyclerStationImg.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        gasImageAdapter = new GasImageAdapter(this, null);
        binding.recyclerStationImg.setAdapter(gasImageAdapter);
        binding.recyclerStation.setAdapter(imageAdapter);
        binding.llCertificates.setOnClickListener(this);
        binding.llCertificatesCarphoto.setOnClickListener(this);
        binding.llChemicalsCarphoto.setOnClickListener(this);
        binding.deleteTv.setOnClickListener(this);
        binding.deleteTv2.setOnClickListener(this);
        binding.deleteTv3.setOnClickListener(this);
        binding.itemTvContactsNumber.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                switch (type) {
                    case 0:

                        File file = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }
                        binding.llCertificates.setVisibility(View.GONE);
                        binding.rlAdd.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.addImg);
                        stationModel.uploadMutiFileModel(file, 0);
                        break;
                    case 1:
                        File file1 = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file1.exists()) {
                            MLog.d("图片", "存在");
                        }
                        binding.llCertificatesCarphoto.setVisibility(View.GONE);
                        binding.rlAdd2.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.addImg2);
                        stationModel.uploadMutiFileModel(file1, 1);
                        break;
                    case 2:
                        File file2 = new File(selectList.get(0).getRealPath());
                        MLog.d("图片路径：", selectList.get(0).getRealPath());
                        if (file2.exists()) {
                            MLog.d("图片", "存在");
                        }
                        binding.llChemicalsCarphoto.setVisibility(View.GONE);
                        binding.rlAdd3.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(selectList.get(0).getRealPath()).into(binding.addImg3);
                        stationModel.uploadMutiFileModel(file2, 2);

                        break;
                    case 3:

                        fileList.clear();
                        urls.clear();
                        for (LocalMedia localMedia : selectList) {
                            File files = new File(localMedia.getRealPath());
                            fileList.add(files);
                            urls.add(localMedia.getRealPath());
                          //  stationModel.uploadMutiFileModel(files, 3);
                        }
                        imageAdapter.setDatas(selectList, urls);
                        imageAdapter.setFileList(fileList);

                        stationModel.uploadMutiFileModel(imageAdapter.getFileList().get(currentImgNum), 3);

                        break;
                }

            }
        }
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        switch (type) {
            case 0:
                businessLicensePic = url;
                break;
            case 1:
                licensePic = url;
                break;
            case 2:
                chemicalsPic = url;
                break;
            case 3:
                uploadStationImgList.add(url);
                if (currentImgNum + 1 != imageAdapter.getFileList().size()) {
                    currentImgNum=currentImgNum+1;
                    stationModel.uploadMutiFileModel(imageAdapter.getFileList().get(currentImgNum), 3);
                }
                break;

        }


    }

    @Override
    protected void init() {
        stationModel.getAddressModel();
        stationModel.getStationInfo();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.right_view:

                binding.deleteTv.setVisibility(View.VISIBLE);
                binding.deleteTv2.setVisibility(View.VISIBLE);
                binding.deleteTv3.setVisibility(View.VISIBLE);
                binding.recyclerStationImg.setVisibility(View.GONE);
                binding.recyclerStation.setVisibility(View.VISIBLE);
                binding.include.rightView.setVisibility(View.GONE);
                adapter.setEdite(true);
                binding.tvAdd.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_add:
                if (adapter.getDatas().size() < 5) {
                    adapter.getDatas().add("");
                    adapter.notifyDataSetChanged();
                } else {
                    MToast.showToast(getActivity(), "最多添加5条服务");
                }

                break;
            case R.id.ll_certificates:
                getCerImage(0);


                break;
            case R.id.ll_certificates_carphoto:
                getCerImage(1);

                break;
            case R.id.ll_chemicals_carphoto:
                getCerImage(2);
                break;

            case R.id.delete_tv:
                binding.llCertificates.setVisibility(View.VISIBLE);
                binding.rlAdd.setVisibility(View.GONE);
                break;
            case R.id.delete_tv_2:
                binding.llCertificatesCarphoto.setVisibility(View.VISIBLE);
                binding.rlAdd2.setVisibility(View.GONE);
                break;
            case R.id.delete_tv_3:
                binding.llChemicalsCarphoto.setVisibility(View.VISIBLE);
                binding.rlAdd3.setVisibility(View.GONE);
                break;
            case R.id.ll_adress:
                toMap(0, 0);
                break;
            case R.id.next_view:
                String name = binding.itemName.getContent();
                String adress = binding.tvAdress.getText().toString();
                String contacts = binding.itemTvContacts.getContent();
                String phone = binding.itemTvContactsNumber.getContent();

                if (TextUtils.isEmpty(name)) {
                    MToast.showToast(this, "请输入加油站名称");
                    return;
                }
                if (TextUtils.isEmpty(adress)) {
                    MToast.showToast(this, "请选择地址");
                    return;
                }
                if (TextUtils.isEmpty(contacts)) {
                    MToast.showToast(this, "请输入联系人");
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    MToast.showToast(this, "请输入手机号");
                    return;
                } else if (!CheckUtils.isMobileNum(phone)) {
                    MToast.showToast(this, "请正确输入手机号");
                    return;
                }
                if (!TextUtils.isEmpty(binding.itemTvFree.getContent())) {
                    stationModel.stationInfo.get().setFavouredPolicy(binding.itemTvFree.getContent());
                }
                if (TextUtils.isEmpty(licensePic)) {
                    MToast.showToast(this, "请添加经营许可证");
                    return;
                }
                if (TextUtils.isEmpty(chemicalsPic)) {
                    MToast.showToast(this, "请添加危险化学品许可证");
                    return;
                }
                if (imageAdapter.getUrls().size() == 0) {
                    MToast.showToast(this, "请添加加油站图片");
                    return;
                }
                stationModel.stationInfo.get().setGasStationName(name);
                stationModel.stationInfo.get().setContactPerson(contacts);
                stationModel.stationInfo.get().setContactTel(phone);
                if (!TextUtils.isEmpty(businessLicensePic)) {
                    stationModel.stationInfo.get().setBusinessLicense(businessLicensePic);
                }
                stationModel.stationInfo.get().setLicense(licensePic);
                stationModel.stationInfo.get().setDangerousGoodsPermit(chemicalsPic);
                if (!TextUtils.isEmpty(stationModel.stationInfo.get().getId())) {
                    uploadStationImgList = imageAdapter.getUrls();
                }
                StringBuffer imgStr = new StringBuffer();
                imgStr.append("[");
                for (String s : uploadStationImgList) {
                    if (!s.equals(uploadStationImgList.get(uploadStationImgList.size() - 1))) {

                        imgStr.append( "\""+s+"\"" );
                        imgStr.append(",");
                    } else {
                        imgStr.append( "\""+s+"\"" );
                    }

                }
                imgStr.append("]");

                stationModel.stationInfo.get().setGasStationImage(imgStr.toString());
                MLog.d("imgLists", stationModel.stationInfo.get().getGasStationImage());
              //  serviceInfo.clear();
                StringBuffer serviceStr = new StringBuffer();
                serviceStr.append("[");
                if (adapter.getDatas().size() > 0) {
                    for (int i = 0; i <= adapter.getDatas().size() - 1; i++) {
                        if (!adapter.getDatas().get(i).equals("")) {
                            if (i!=adapter.getDatas().size()-1) {

                                serviceStr.append( "\""+adapter.getDatas().get(i)+"\"" );
                                serviceStr.append(",");
                            } else {
                                serviceStr.append( "\""+adapter.getDatas().get(i)+"\"" );
                            }

                        }
                    }
                    serviceStr.append("]");

                    stationModel.stationInfo.get().setGasStationServer(serviceStr.toString());
                    MLog.d("serviceList", stationModel.stationInfo.get().getGasStationServer());
                }


                stationModel.editeInfo();


                break;
        }
    }

    public void setType(int type) {
        this.type = type;
    }

    private void getCerImage(int type) {
        this.type = type;
        MLog.d("type == ", "" + type);
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        Log.v("public==source", datas.size() + "");
        initJsonData();
    }

    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }


    }

    public void toMap(double la, double lo) {
        MapAdressDialog dialog = new MapAdressDialog(getActivity(), null);
        dialog.setLocation(la, lo);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogs) {
                dialog.destoryMap();
            }
        });
        dialog.setDialogClickCallBack(new MapAdressDialog.DialogClickCallBack() {
            @Override
            public void onClickMarker(String adress, String pro, String city, String area, double latitude, double longtitude) {


                stationModel.stationInfo.get().setLatitude(latitude);
                stationModel.stationInfo.get().setLongitude(longtitude);
                stationModel.stationInfo.get().setProvinceName(pro);
                stationModel.stationInfo.get().setCityName(city);
                stationModel.stationInfo.get().setDistrictName(area);
                binding.tvAdress.setText(adress);
                stationModel.stationInfo.get().setGasStationAddress(adress);

                for (AddressEntity entity : addressEntityList) {
                    if (entity.getName().equals(pro)) {
                        MLog.d("locationOffOder", "proON " + entity.getNo() + "  " + entity.getName());

                        stationModel.stationInfo.get().setProvinceNo(entity.getNo());

                        break;
                    }

                }
                boolean isbreak1 = false;

                for (int i = 0; i < opt2.size(); i++) {
                    for (int j = 0; j < opt2.get(i).size(); j++) {
                        if (opt2.get(i).get(j).getName().equals(city)) {
                            MLog.d("locationOffOder", "cityON1 " + opt2.get(i).get(j).getNo() + "  ");

                            stationModel.stationInfo.get().setCityNo(opt2.get(i).get(j).getNo());

                            isbreak1 = true;
                            break;
                        }
                    }
                    if (isbreak1) {
                        break;
                    }

                }
                boolean isbreak2 = false;
                for (int i = 0; i < opt3.size(); i++) {
                    for (int j = 0; j < opt3.get(i).size(); j++) {
                        for (int n = 0; n < opt3.get(i).get(j).size(); n++) {
                            if (opt3.get(i).get(j).get(n) != null) {
                                MLog.d("locationOffOder", "Direction " + opt3.get(i).get(j).get(n).getName() + "  ");
                                if (opt3.get(i).get(j).get(n).getName().equals(area)) {
                                    MLog.d("locationOffOder", "cityON2 " + opt3.get(i).get(j).get(n).getNo() + "  ");

                                    stationModel.stationInfo.get().setDistrictNo(opt3.get(i).get(j).get(n).getNo());

                                    isbreak2 = true;
                                    break;
                                }
                            }
                        }
                        if (isbreak2) {
                            break;
                        }
                    }
                    if (isbreak2) {
                        break;
                    }
                }
            }
        });
        dialog.show();
    }

    GasStationInfoEntity infoEntity;

    public void getInfo(GasStationInfoEntity infoEntity) {
        this.infoEntity = infoEntity;

        if (infoEntity.getId() != 0) {
            binding.itemName.setContent(infoEntity.getGasStationName());
            binding.tvAdress.setText(infoEntity.getGasStationAddress());
            binding.itemTvContacts.setContent(infoEntity.getContactPerson());
            binding.itemTvContactsNumber.setContent(infoEntity.getContactTel());
            binding.itemTvFree.setContent(infoEntity.getFavouredPolicy());
            adapter.setDatas(infoEntity.getGasStationServerArr());
            if (!TextUtils.isEmpty(infoEntity.getBusinessLicense())) {
                businessLicensePic = infoEntity.getBusinessLicense();
                binding.llCertificates.setVisibility(View.GONE);
                binding.rlAdd.setVisibility(View.VISIBLE);
                binding.deleteTv.setVisibility(View.GONE);
                Glide.with(getActivity()).load(infoEntity.getBusinessLicense()).into(binding.addImg);
            }
            licensePic = infoEntity.getLicense();
            binding.llCertificatesCarphoto.setVisibility(View.GONE);
            binding.rlAdd2.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(infoEntity.getLicense()).into(binding.addImg2);
            chemicalsPic = infoEntity.getDangerousGoodsPermit();
            binding.llChemicalsCarphoto.setVisibility(View.GONE);
            binding.rlAdd3.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(infoEntity.getDangerousGoodsPermit()).into(binding.addImg3);
            uploadStationImgList.addAll(infoEntity.getGasStationImage());

            imageAdapter.setNetImgList(uploadStationImgList);
            gasImageAdapter.setDatas(infoEntity.getGasStationImage());
            stationModel.stationInfo.get().setLongitude(infoEntity.getLongitude());
            stationModel.stationInfo.get().setLatitude(infoEntity.getLatitude());
            stationModel.stationInfo.get().setProvinceName(infoEntity.getProvinceName());
            stationModel.stationInfo.get().setProvinceNo(infoEntity.getProvinceNo());
            stationModel.stationInfo.get().setCityName(infoEntity.getCityName());
            stationModel.stationInfo.get().setCityNo(infoEntity.getCityNo());
            stationModel.stationInfo.get().setDistrictName(infoEntity.getDistrictName());
            stationModel.stationInfo.get().setDistrictNo(infoEntity.getDistrictNo());
            stationModel.stationInfo.get().setGasStationAddress(infoEntity.getGasStationAddress());
            stationModel.stationInfo.get().setId("" + infoEntity.getId());

            binding.deleteTv2.setVisibility(View.GONE);
            binding.deleteTv3.setVisibility(View.GONE);
            binding.include.rightView.setText("编辑");
            binding.include.rightView.setVisibility(View.VISIBLE);
            binding.include.rightView.setOnClickListener(this);
            if(infoEntity.getGasStationServerArr()!=null&&infoEntity.getGasStationServerArr().size()>0) {
                adapter.setDatas(infoEntity.getGasStationServerArr());
                adapter.setEdite(false);
            }
            binding.recyclerStationImg.setVisibility(View.VISIBLE);
            binding.recyclerStation.setVisibility(View.GONE);
            binding.tvAdd.setVisibility(View.GONE);
        }else{
            adapter.setEdite(true);
        }
    }

}
